package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

/**
 * 将字符串转换为枚举类型。通用类型转换器。
 */
@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {

        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                for (T type : targetType.getEnumConstants()) {
                    if (type.getCode().equals(Integer.valueOf(source))) {
                        return type;
                    }
                }
                throw new IllegalArgumentException("不合法参数-" + source);
            }
        };
    }
}
